//
//  SearchResultsVC.m
//  AAIM
//
//  Created by awh on 2019/12/6.
//  Copyright © 2019年 AAIM. All rights reserved.
//

#import "SearchResultsVC.h"
#import "FirendsTableViewCell.h"
#import "FriendsInfoViewController.h"
#import "GroupInfoViewController.h"
#import "PublicArticleViewController.h"
#import "ContactRequestLogic.h"
#import "ContactModel.h"
#import "CustomsSearchBtn.h"
#import "SearchFriendsViewController.h"
#import "ChatViewController.h"
#import "BTMessageModel.h"
#import "ChatRecodeViewController.h"

@interface SearchResultsVC ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>
{
    CustomsSearchBtn * btn;
    CustomsSearchBtn * btn1;
    CustomsSearchBtn * btn2;
}
@property (nonatomic,strong)UITableView * searchResultsTable;//搜索历史
@property (nonatomic,strong)NSMutableArray*searchResultsArray;
@property (nonatomic,strong)UISearchBar * searchBar;
@property (nonatomic,strong)MJTableViewNullDataView *nullDataView;
@property (nonatomic,strong) UIView *titleView;
@property (nonatomic,strong)UITextField *textField;
@property (nonatomic,strong)UILabel *searchTitle;
@property (nonatomic,strong)UIView * tipView;
@property (nonatomic,strong)UILabel * tipLabel;

@property (nonatomic,strong)NSArray * dataAry;

@property (nonatomic,strong)UIView *footView;

@property (nonatomic,assign)NSInteger cateIndex;//搜索类别0本地，1好友，2群，3公众号
@property (nonatomic,strong)NSMutableArray * friendAndGroupDataAry;//本地好友和群搜索数据
@property (nonatomic,strong)NSMutableArray * friendsArr;//联系人
@property (nonatomic,strong)NSMutableArray * groupsArr;//群聊
@property (nonatomic,strong)NSMutableArray * localChatDataAry;//本地聊天数据
@property (nonatomic,assign)BOOL noFriend;//确定区头名称 1无好友
@property (nonatomic,assign)BOOL noGroup;//无群聊
@property (nonatomic,assign)BOOL noChat;//无聊天记录
@property (nonatomic,assign)BOOL noPublic;//无公众号
@property (nonatomic,strong)UILabel * tipLbl;

@end

@implementation SearchResultsVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
    if ([_controllerType isEqualToString:@"searchFriend"]) {
        _textField.placeholder=@"搜索好友";
    }else
    {
        //        _textField.placeholder=@"搜索好友/群/公众号/服务号";
        _textField.placeholder=@"搜索好友/群/服务号";
        _cateIndex = 0;
    }
#pragma mark -键盘弹出添加监听事件
    // 键盘出现的通知
    //    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShown:) name:UIKeyboardDidShowNotification object:nil];
    //    // 键盘消失的通知
    //    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillBeHiden:) name:UIKeyboardWillHideNotification object:nil];
    // Do any additional setup after loading the view.
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    //    [self.textField becomeFirstResponder];
}

//#pragma mark -键盘监听方法
//- (void)keyboardWasShown:(NSNotification *)notification
//{
//    // 获取键盘的高度
//    CGRect frame = [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
//    CGFloat height = SCREEN_HEIGHT - 64 - frame.size.height;
//
//    if (height < 455.5) {
//        NSLog(@"高度1");
////        self.textFiledScrollView.frame = CGRectMake(0, 64, kViewWidth, height);
//    }
//
////    if (![self.gk_navTitleTextView.text isEqualToString:@""]) {
////        self.gk_navTitleTextView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
////    } else {
////        self.gk_navTitleTextView.contentInset = UIEdgeInsetsMake(20, 0, -20, 0);// 光标偏移
////    }
//    NSLog(@"高度2");
////    [self contentSizeToFit];// 垂直居中
//}
//- (void)keyboardWillBeHiden:(NSNotification *)notification
//{
//    NSLog(@"高度3");
////    self.textFiledScrollView.frame = CGRectMake(0, 64, kViewWidth, 455.5);
//}

- (void)setupUI {
    UIButton *leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [leftBtn setImage:[UIImage imageNamed:@"bar_back1"] forState:UIControlStateNormal];
    [leftBtn setImageEdgeInsets:UIEdgeInsetsMake(-2, 5, -2, -5)];
    leftBtn.jk_touchAreaInsets = UIEdgeInsetsMake(5, 5, 5, 5);
    leftBtn.frame=CGRectMake(0, 0, 30, 44);
    //    leftBtn.backgroundColor=[UIColor redColor];
    [leftBtn addTarget:self action:@selector(leftBtnBtnDidClickAction:) forControlEvents:UIControlEventTouchUpInside];
    //    [leftBtn sizeToFit];
    
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithCustomView:leftBtn];
    self.gk_navigationItem.leftBarButtonItems = @[leftItem];
    self.gk_navigationItem.titleView = self.titleView;
    
    
    _searchResultsTable=[[UITableView alloc]initWithFrame:CGRectMake(0, NavigationBarHeight, SCREEN_WIDTH,SCREEN_HEIGHT-NavigationBarHeight) style:UITableViewStylePlain];
    _searchResultsTable.delegate=self;
    _searchResultsTable.dataSource=self;
    _searchResultsTable.rowHeight=60;
    if ([_controllerType isEqualToString:@"searchFriend"]) {
        _searchResultsTable.tableFooterView=[UIView new];
    }else
    {
        
        NSArray * titleArray = @[@"搜索ID",@"网络查找群",@"搜索公众号/服务号"];
        NSString * str;
        if (!_textField.text) {
            str = @"";
        }else{
            str = _textField.text;
        }
        
        self.footView.hidden = YES;
        btn =[[CustomsSearchBtn alloc]initWithFrame:CGRectMake(0, 0, _searchResultsTable.width, 53)];
        btn.nameLabel.attributedText = [self getAttributeWith:@[titleArray[0]] string:[NSString stringWithFormat:@"%@%@",titleArray[0],str] orginFont:14 orginColor:KHEXCOLOR(@"#4795EF") attributeFont:14 attributeColor:[UIColor colorWithHexString:@"#262B2F"]];
        [btn addTarget:self action:@selector(touchActive:) forControlEvents:UIControlEventTouchUpInside];
        btn.tag = 10;
        [self.footView addSubview:btn];
        btn1 =[[CustomsSearchBtn alloc]initWithFrame:CGRectMake(0, 53, _searchResultsTable.width, 53)];
        btn1.nameLabel.attributedText = [self getAttributeWith:@[titleArray[1]] string:[NSString stringWithFormat:@"%@%@",titleArray[1],str] orginFont:14 orginColor:KHEXCOLOR(@"#4795EF") attributeFont:14 attributeColor:[UIColor colorWithHexString:@"#262B2F"]];
        [btn1 addTarget:self action:@selector(touchActive:) forControlEvents:UIControlEventTouchUpInside];
        btn1.tag = 11;
        [self.footView addSubview:btn1];
        btn2 =[[CustomsSearchBtn alloc]initWithFrame:CGRectMake(0, 106, _searchResultsTable.width, 53)];
        btn2.nameLabel.attributedText = [self getAttributeWith:@[titleArray[2]] string:[NSString stringWithFormat:@"%@%@",titleArray[2],str] orginFont:14 orginColor:KHEXCOLOR(@"#4795EF") attributeFont:14 attributeColor:[UIColor colorWithHexString:@"#262B2F"]];
        [btn2 addTarget:self action:@selector(touchActive:) forControlEvents:UIControlEventTouchUpInside];
        btn2.tag = 12;
        [self.footView addSubview:btn2];
        _searchResultsTable.tableFooterView=self.footView;
    }
    
    _searchResultsTable.showsVerticalScrollIndicator = NO;
    _searchResultsTable.backgroundColor=[UIColor whiteColor];
    [_searchResultsTable registerClass:[FirendsTableViewCell class] forCellReuseIdentifier:@"searchCell"];
    _searchResultsTable.separatorStyle=UITableViewCellSeparatorStyleNone;
    [self.view addSubview:self.searchResultsTable];
    //    [self.searchResultsTable addSubview:self.nullDataView];
    
    _searchTitle=[[UILabel alloc]initWithFrame:CGRectMake(40, NavigationBarHeight+80, SCREEN_WIDTH-80, 30)];
    _searchTitle.text=@"暂无搜索内容";
    _searchTitle.textAlignment=1;
    _searchTitle.hidden=YES;
    _searchTitle.font=[UIFont systemFontOfSize:15];
    _searchTitle.textColor=KHEXCOLOR(kGrayColor_99);
    [self.view addSubview:self.searchTitle];
    
    
    if ([_controllerType isEqualToString:@"searchFriend"]) {
        [self.view addSubview:self.tipView];
        [self.tipView addSubview:self.tipLabel];
        _tipView.hidden = YES;
        [_tipView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.view.mas_left);
            make.top.equalTo(self.view.mas_top).offset(kTopHeight);
            make.right.equalTo(self.view.mas_right);
            make.height.offset(56.f);
        }];
        
        UIImageView * leftImageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"搜索中"]];
        leftImageView.layer.cornerRadius = 5;
        leftImageView.layer.masksToBounds = YES;
        [_tipView addSubview:leftImageView];
        
        [leftImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.tipView.mas_left).offset(15.f);
            make.centerY.equalTo(self.tipView.mas_centerY);
            make.size.mas_equalTo(CGSizeMake(30.f, 30.f));
        }];
        
        [_tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(leftImageView.mas_right).offset(8.0f);
            make.centerY.equalTo(leftImageView.mas_centerY);
            make.right.equalTo(self.tipView.mas_right).offset(-15.f);
        }];
    }
    _tipLbl = [[UILabel alloc]init];
    _tipLbl.text = @"搜索指定内容";
    _tipLbl.textColor = KHEXCOLOR(@"#D8D8D8");
    _tipLbl.font = kMainFont(12.f);
    
    [self.view addSubview:_tipLbl];
    [_tipLbl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top).offset(16+kTopHeight);
        make.centerX.equalTo(self.view.mas_centerX);
    }];
    
    
}

- (void)touchActive:(CustomsSearchBtn *)sender{
    switch (sender.tag) {
        case 10:
            _cateIndex = 1;
            [self searchActionWithKeyWord:_textField.text];
            break;
        case 11:
            _cateIndex = 2;
            [self searchActionWithKeyWord:_textField.text];
            break;
        default:
            _cateIndex = 3;
            NSLog(@"搜索公众号");
            [self searchActionWithKeyWord:_textField.text];
            break;
    }
}


-(void)textFieldTextChange:(UITextField*)textField
{
    [self.localChatDataAry removeAllObjects];
    [self.friendAndGroupDataAry removeAllObjects];
    [self.friendsArr removeAllObjects];
    [self.groupsArr removeAllObjects];
    self.footView.hidden = NO;
    if (textField.text.length == 0) {
        _tipLbl.hidden = NO;
    }else{
        _tipLbl.hidden = YES;
    }
    
    btn.nameLabel.attributedText = [self getAttributeWith:@[@"搜索ID"] string:[NSString stringWithFormat:@"搜索ID %@",textField.text] orginFont:14 orginColor:KHEXCOLOR(@"#4795EF") attributeFont:14 attributeColor:[UIColor colorWithHexString:@"#262B2F"]];
    
    btn1.nameLabel.attributedText = [self getAttributeWith:@[@"网络查找群"] string:[NSString stringWithFormat:@"网络查找群 %@",textField.text] orginFont:14 orginColor:KHEXCOLOR(@"#4795EF") attributeFont:14 attributeColor:[UIColor colorWithHexString:@"#262B2F"]];
    
    btn2.nameLabel.attributedText = [self getAttributeWith:@[@"搜索公众号/服务号"] string:[NSString stringWithFormat:@"搜索公众号/服务号 %@",textField.text] orginFont:14 orginColor:KHEXCOLOR(@"#4795EF") attributeFont:14 attributeColor:[UIColor colorWithHexString:@"#262B2F"]];
    
    if (![CommonTools isEmpty:textField.text]) {
        //好友
        
        NSArray * myFriendAry = [[UserDataBaseTool shareUserDataBaseTool] queryAllFriends];
        [myFriendAry enumerateObjectsUsingBlock:^(ContactModel * obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([obj.nickname containsString:textField.text]||[obj.username containsString:textField.text]) {
                [self.friendsArr addObject:obj];
            }
        }];
        if (self.friendsArr.count != 0) {
            _noFriend = NO;
            [self.friendAndGroupDataAry addObject:self.friendsArr];
        }else{
            _noFriend = YES;
        }
        //        群
        NSArray * groups = [[UserDataBaseTool shareUserDataBaseTool] queryAllGroups];
        [groups enumerateObjectsUsingBlock:^(ContactModel * obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([obj.groupName containsString:textField.text]) {
                [self.groupsArr addObject:obj];
            }
        }];
        if (self.groupsArr.count != 0) {
            _noGroup = NO;
            [self.friendAndGroupDataAry addObject:self.groupsArr];
        }else{
            _noGroup = YES;
        }
        //        公众号
        NSArray * publicArray = [[UserDataBaseTool shareUserDataBaseTool]queryAllPublic];
        NSMutableArray * publicArr = [NSMutableArray array];
        [publicArray enumerateObjectsUsingBlock:^(PublicModel * puModel, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([puModel.title containsString:textField.text]||[puModel.describe containsString:textField.text]) {
                [publicArr addObject:puModel];
            }
        }];
        if (publicArr.count !=0) {
            _noPublic = NO;
            [self.friendAndGroupDataAry addObject:publicArr];
        }else{
            _noPublic = YES;
        }
        //        聊天记录
        NSArray * friendChatAry = [[ChatMessagesDataBase shareChatMessagesDataBase] queryFriendsMessagesWithKeyWord:textField.text];//搜索出来的相关聊天记录
        NSMutableArray * chatRecodingAry = [NSMutableArray array];//总的群和好友的聊天数据
        
        [friendChatAry enumerateObjectsUsingBlock:^(BTMessageModel * obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if (chatRecodingAry.count == 0) {
                NSMutableArray * chatAry = [NSMutableArray array];
                [chatAry addObject:obj];
                [chatRecodingAry addObject:chatAry];
            }else{
                __block BOOL isAdd = NO;
                [chatRecodingAry enumerateObjectsUsingBlock:^(NSMutableArray * chatAry, NSUInteger idx1, BOOL * _Nonnull stop1) {
                    
                    BTMessageModel * msgModel = chatAry[0];//数组中是同一个人的数据，取第一个比较就行
                    
                    if (msgModel.messageDirection == MessageDirectionSend) {
                        if ([msgModel.f_uuid isEqualToString:obj.f_uuid]) {
                            isAdd = YES;
                            [chatAry addObject:obj];
                            *stop1 = YES;
                        }
                    }else{
                        if (msgModel.receiveUid == obj.receiveUid) {
                            isAdd = YES;
                            [chatAry addObject:obj];
                            *stop1 = YES;
                        }
                    }
                    
                }];
                if (!isAdd) {
                    NSMutableArray * chatAry = [NSMutableArray array];
                    [chatAry addObject:obj];
                    [chatRecodingAry addObject:chatAry];
                }
            }
        }];
        
        
        //                群聊天记录
        
        NSArray * groupChatAry = [[GroupMessageDataBase shareGroupMessageDataBase]queryGroupMessagesWithKeyWord:textField.text];
        NSMutableArray * groupAry = [NSMutableArray array];
        
        [groupChatAry enumerateObjectsUsingBlock:^(BTMessageModel * obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if (groupAry.count == 0) {
                NSMutableArray * ary = [NSMutableArray array];
                [ary addObject:obj];
                [groupAry addObject:ary];
            }else{
                __block BOOL isAdd = NO;
                [groupAry enumerateObjectsUsingBlock:^(NSMutableArray * ary2, NSUInteger idx2, BOOL * _Nonnull stop2) {
                    
                    BTMessageModel * msgModel = ary2[0];//同上
                    if ([msgModel.gId isEqualToString:obj.gId]) {
                        isAdd = YES;
                        [ary2 addObject:obj];
                        *stop2 = YES;
                    }
                }];
                
                //如果数组中都没有的话，就创建一个数组，把聊天记录存放到该数组
                if (!isAdd) {
                    NSMutableArray * chatAry = [NSMutableArray array];
                    [chatAry addObject:obj];
                    [groupAry addObject:chatAry];
                }
            }
        }];
        if (groupAry.count != 0) {
            [chatRecodingAry addObjectsFromArray:groupAry];
        }
        if (chatRecodingAry.count != 0) {
            [self.localChatDataAry addObjectsFromArray:chatRecodingAry];
        }
        if (self.localChatDataAry.count != 0) {
            _noChat = NO;
            [self.friendAndGroupDataAry addObject:self.localChatDataAry];
        }else{
            _noChat = YES;
        }
    }else{
        [self.localChatDataAry removeAllObjects];
        [self.friendAndGroupDataAry removeAllObjects];
        [self.friendsArr removeAllObjects];
        [self.groupsArr removeAllObjects];
    }
    [self.searchResultsTable reloadData];
    
}

- (void)textFieldDidBeginEditing:(UITextField *)textField{
    //    _searchResultsTable.frame.origin.y = NavigationBarHeight+56.f;
    if ([_controllerType isEqualToString:@"searchFriend"]) {
        _tipView.hidden = NO;
        _searchResultsTable.top = _tipView.bottom;
    }else{
        self.footView.hidden = NO;
        self.tipLbl.hidden = YES;
    }
    
}

- (void)textFieldDidEndEditing:(UITextField *)textField{
    if ([_controllerType isEqualToString:@"searchFriend"]) {
        _tipView.hidden = YES;
        _textField.text = nil;
        _searchResultsTable.top = self.view.top;
    }else{
        if (textField.text.length == 0) {
            self.footView.hidden = YES;
            self.tipLbl.hidden = NO;
        }else{
            self.footView.hidden = NO;
            self.tipLbl.hidden = YES;
        }
        
    }
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if (![NSObject ldy_isEmpty:textField.text]) {
        //        [self searchActionWithKeyWord:textField.text];
    }else
    {
        if ([_controllerType isEqualToString:@"searchFriend"]) {
            _searchTitle.hidden=YES;
            _tipView.hidden = YES;
            _searchResultsTable.top = self.view.top;
        }
        
        _textField.text = nil;
    }
    return YES;
}

-(void)searchActionWithKeyWord:(NSString*)keyWord
{
    if ([CommonTools isEmpty:keyWord]) {
        [self showTipHudWithText:@"请输入搜索内容"];
        return;
    }
    [self.searchResultsArray removeAllObjects];
    if (_cateIndex == 1) {
        [ContactRequestLogic requestSearchFriendQueryWithQuery:keyWord Success:^(NSDictionary * _Nonnull Dict) {
            KWeakSelf;
            AAIMLog(@"搜索手机号/ID===%@",Dict);
            NSMutableArray * dataModelArr = [NSMutableArray array];
            
            for (NSDictionary * dic in Dict[@"data"][@"list"]) {
                ContactModel * model = [ContactModel mj_objectWithKeyValues:dic];
                [dataModelArr addObject:model];
            }
            
            
            SearchFriendsViewController * searchFriendVC = [[SearchFriendsViewController alloc]init];
            searchFriendVC.pageType = @"searchUserID";
            searchFriendVC.searchIDAry = dataModelArr;
            searchFriendVC.searchContent = keyWord;
            [weakSelf.navigationController pushViewController:searchFriendVC animated:YES];
        } failure:^(NSString * _Nonnull errMsg) {
            [self showTipHudWithText:errMsg];
        }];
        
    }else if(_cateIndex == 2){
        [ContactRequestLogic  requestSearchGroupNameWithQuery:keyWord Success:^(NSDictionary * _Nonnull Dict) {
            AAIMLog(@"搜索群聊===%@",Dict);
            KWeakSelf;
            NSArray * dataAry =Dict[@"data"];
            
            NSMutableArray * dataModelArr = [NSMutableArray array];
            
            for (NSDictionary * dic in dataAry) {
                ContactModel * model =[ContactModel mj_objectWithKeyValues:dic];
                [dataModelArr addObject:model];
                
            }
            SearchFriendsViewController * searchFriendVC = [[SearchFriendsViewController alloc]init];
            searchFriendVC.pageType = @"searchGroupName";
            searchFriendVC.searchIDAry = dataModelArr;
            searchFriendVC.searchContent = keyWord;
            [weakSelf.navigationController pushViewController:searchFriendVC animated:YES];
            
        } failure:^(NSString * _Nonnull errMsg) {
            [self showTipHudWithText:errMsg];
        }];
    }else if (_cateIndex ==3){
        [ContactRequestLogic requestSearchPublicNameWithQuery:keyWord Success:^(NSDictionary * _Nonnull Dict) {
            NSLog(@"公众号：%@",Dict);
            KWeakSelf;
            NSArray * dataAry =Dict[@"data"];
            
            NSMutableArray * dataModelArr = [NSMutableArray array];
            
            for (NSDictionary * dic in dataAry) {
                PublicModel * model =[PublicModel mj_objectWithKeyValues:dic];
                [dataModelArr addObject:model];
                
            }
            SearchFriendsViewController * searchFriendVC = [[SearchFriendsViewController alloc]init];
            searchFriendVC.pageType = @"searchService";
            searchFriendVC.searchIDAry = dataModelArr;
            [weakSelf.navigationController pushViewController:searchFriendVC animated:YES];
            
        } failure:^(NSString * _Nonnull errMsg) {
            [self showTipHudWithText:errMsg];
        }];
    }else{
        //本地搜索
    }
    
    
    
    
    /*
     if ([self.collerType isEqualToString:@"4"]) {
     NSMutableArray * groupMembersArray=[[NSMutableArray alloc]init];
     NSMutableArray * friendMembersArray=[[NSMutableArray alloc]init];
     [self.searchResultsArray removeAllObjects];
     NSArray * allFriendsArray=[[LoginManager shareLoginManager].userDataBase ReadLoginUserFirendsData];
     //        BTIMLog(@"所有人=%@",allFriendsArray);
     if (allFriendsArray.count>0) {
     for (NSDictionary * friendDic in allFriendsArray) {
     //                BTIMLog(@"==friendDic  好友===%@",friendDic);
     if ([[NSString stringWithFormat:@"%@",friendDic[@"username"]] containsString:keyWord]) {
     ContactorModel * model =[ContactorModel mj_objectWithKeyValues:friendDic];
     model.is_group=@"friend";
     [friendMembersArray addObject:model];
     //[self.searchResultsArray addObject:model];
     }else if ([[NSString stringWithFormat:@"%@",friendDic[@"nickname"]] containsString:keyWord])
     {
     ContactorModel * model =[ContactorModel mj_objectWithKeyValues:friendDic];
     model.is_group=@"friend";
     [friendMembersArray addObject:model];
     
     }else if ([[NSString stringWithFormat:@"%@",friendDic[@"remark"]] containsString:keyWord])
     {
     ContactorModel * model =[ContactorModel mj_objectWithKeyValues:friendDic];
     model.is_group=@"friend";
     [friendMembersArray addObject:model];
     }
     
     }
     }
     NSArray * allGroupInfoArray= [[LoginManager shareLoginManager].userDataBase ReadLoginUserGroupData];
     //        BTIMLog(@"所有群=%@",allGroupInfoArray);
     if (allGroupInfoArray.count>0) {
     for (NSDictionary * groupDic in allGroupInfoArray) {
     if ([[NSString stringWithFormat:@"%@",groupDic[@"groupname"]] containsString:keyWord]) {
     ContactorModel * model =[ContactorModel mj_objectWithKeyValues:groupDic];
     model.is_group=@"group";
     [groupMembersArray addObject:model];
     }
     }
     }
     if (groupMembersArray.count>0&&friendMembersArray.count>0) {
     self.searchTitle.hidden=YES;
     self.searchResultsArray=[NSMutableArray arrayWithObjects:friendMembersArray,groupMembersArray, nil];
     
     }else if (groupMembersArray.count==0&&friendMembersArray.count==0)
     {
     self.searchTitle.hidden=NO;
     
     }else if (groupMembersArray.count>0&&friendMembersArray.count==0)
     {
     self.searchTitle.hidden=YES;
     self.searchResultsArray=[NSMutableArray arrayWithObjects:groupMembersArray, nil];
     }else if (groupMembersArray.count==0&&friendMembersArray.count>0)
     {
     self.searchTitle.hidden=YES;
     self.searchResultsArray=[NSMutableArray arrayWithObjects:friendMembersArray, nil];
     }
     [self.searchResultsTable reloadData];
     }else
     {
     KWeakSelf;
     NSInteger type;
     NSString * titleStr;
     if ([self.collerType isEqualToString:@"搜索联系人"]) {
     type=0;
     titleStr=@"相关寞友";
     }else {
     type=1;
     titleStr=@"相关群聊";
     }
     
     [self.searchResultsArray removeAllObjects];
     [ContactorsRequestLogic UserSearchFirendInfoWithkeyword:keyWord type:type userInvitationCode:[LoginManager shareLoginManager].userModel.userInvitationCode Success:^(NSDictionary * _Nonnull Dict) {
     //            BTIMLog(@"搜索结果=%@",Dict);
     NSArray * dataArray=Dict[@"obj"];
     if ([dataArray isKindOfClass:[NSArray class]] && dataArray.count > 0){
     self.nullDataView.hidden=YES;
     self.searchTitle.hidden=YES;
     
     for (NSDictionary* dic in dataArray) {
     ContactorModel * model =[ContactorModel mj_objectWithKeyValues:dic];
     [self.searchResultsArray addObject:model];
     }
     [self.searchResultsTable reloadData];
     }else
     {
     self.nullDataView.hidden=NO;
     }
     
     } failure:^(NSString * _Nonnull errMsg) {
     
     [self.searchResultsArray removeAllObjects];
     [self.searchResultsTable reloadData];
     weakSelf.searchTitle.hidden=NO;
     weakSelf.searchTitle.text=[NSString stringWithFormat:@"没有找到 ‘%@’ %@",keyWord,titleStr];
     //        [self showTipHudWithText:errMsg];
     }];
     }
     */
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    //    if ([self.collerType isEqualToString:@"4"]) {
    return 23;
    //    }else
    //    {
    //        return 0.0001;
    //    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 159.f;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    //    if ([self.collerType isEqualToString:@"4"]) {
    UIView *view = [[UIView alloc] init];
    view.backgroundColor = [UIColor whiteColor];
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(15, 10, tableView.frame.size.width - 20, 15)];
    label.backgroundColor =  [UIColor whiteColor];
    label.font = [UIFont systemFontOfSize:14];
    label.textAlignment=0;
    label.textColor=KHEXCOLOR(@"#AFAFAF");
    NSString *title ;
    if (section == 0) {
        if (_noFriend) {
            if (_noGroup) {
                if (_noPublic) {
                    if (!_noChat){
                        title = @"聊天记录";
                    }
                    
                }else{
                    title = @"公众号";
                }
                
            }else{
                title = @"群聊";
            }
        }else{
            title = @"好友";
        }
        
    }else if (section == 1){
        if (!_noFriend&&!_noGroup) {
            title = @"群聊";
        }else{
            if (_noFriend&&!_noGroup) {
                if (_noPublic) {
                    title = @"聊天记录";
                }else{
                    title = @"公众号";
                }
            }else if (!_noPublic){
                title = @"公众号";
            }else{
                title = @"聊天记录";
            }
        }
    }else if (section == 2){
        if (!_noFriend&&!_noGroup&&!_noPublic) {
            title = @"公众号";
        }else{
            if (_noGroup&&_noFriend&&_noPublic) {
                title = @"聊天记录";
            }else{
                if (_noPublic) {
                    title = @"聊天记录";
                }else{
                    if (!_noFriend&&!_noPublic&&!_noGroup) {
                        title = @"公众号";
                    }else{
                        title = @"聊天记录";
                    }
                    
                }
            }
        }
    }else{
        title = @"聊天记录";
    }
    
    label.text = [NSString stringWithFormat:@"%@", title];
    [view addSubview:label];
    return view;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    if (indexPath.section==0) {
        if (_noFriend) {
            if (_noGroup) {
                if (_noPublic) {
                    
                    //无群聊无好友，就聊天记录
                    ChatRecodeViewController * chatRecodeVC = [[ChatRecodeViewController alloc]init];
                    chatRecodeVC.dataAry = self.friendAndGroupDataAry[indexPath.section][indexPath.row];
                    [self.navigationController pushViewController:chatRecodeVC animated:YES];
                }else{
                    //公众号
                    PublicModel * model = _friendAndGroupDataAry[indexPath.section][indexPath.row];
                    PublicArticleViewController*vc=[[PublicArticleViewController alloc]init];
                    vc.publicUdid = model.udid;
                    vc.gk_navTitle = model.title;
                    [self.navigationController pushViewController:vc animated:YES];
                }
            }else{
                //群聊
                ChatViewController * chatVC=[[ChatViewController alloc]init];
                ContactModel * model = self.friendAndGroupDataAry[indexPath.section][indexPath.row];
                chatVC.receiverId = model.user_id;
                chatVC.gk_navTitle = model.groupName;
                chatVC.chatType = ChatTypeGroup;
                [self.navigationController pushViewController:chatVC animated:YES];
            }
        }else{
            //好友
            ContactModel * model = self.friendAndGroupDataAry[indexPath.section][indexPath.row];
            FriendsInfoViewController * vc =[[FriendsInfoViewController alloc]init];
            vc.Fuuid = model.fuuid;
            vc.type = @"search";
            [self.navigationController pushViewController:vc animated:YES];
        }
        
    }else if(indexPath.section==1)
    {
        if (_noGroup&_noFriend&&_noPublic) {
            //无群聊无好友，就聊天记录
            ChatRecodeViewController * chatRecodeVC = [[ChatRecodeViewController alloc]init];
            chatRecodeVC.dataAry = self.friendAndGroupDataAry[indexPath.section][indexPath.row];
            [self.navigationController pushViewController:chatRecodeVC animated:YES];
        }else if(_noFriend &&_noGroup&&!_noPublic){
            //聊天记录
            ChatRecodeViewController * chatRecodeVC = [[ChatRecodeViewController alloc]init];
            chatRecodeVC.dataAry = self.friendAndGroupDataAry[indexPath.section][indexPath.row];
            [self.navigationController pushViewController:chatRecodeVC animated:YES];
        }else if(_noFriend &&!_noGroup&&!_noPublic){
            PublicModel * model = _friendAndGroupDataAry[indexPath.section][indexPath.row];
            PublicArticleViewController*vc=[[PublicArticleViewController alloc]init];
            vc.publicUdid = model.udid;
            vc.gk_navTitle = model.title;
            [self.navigationController pushViewController:vc animated:YES];
        }else if(_noFriend && _noGroup){
            PublicModel * model = _friendAndGroupDataAry[indexPath.section][indexPath.row];
            PublicArticleViewController*vc=[[PublicArticleViewController alloc]init];
            vc.gk_navTitle = model.title;
            vc.publicUdid = model.udid;
            [self.navigationController pushViewController:vc animated:YES];
            
        }else{
            if (_noGroup) {
                //聊天记录
                ChatRecodeViewController * chatRecodeVC = [[ChatRecodeViewController alloc]init];
                chatRecodeVC.dataAry = self.friendAndGroupDataAry[indexPath.section][indexPath.row];
                [self.navigationController pushViewController:chatRecodeVC animated:YES];
            }else{
                //群聊
                ChatViewController * chatVC=[[ChatViewController alloc]init];
                ContactModel * model = self.friendAndGroupDataAry[indexPath.section][indexPath.row];
                chatVC.receiverId = model.user_id;
                chatVC.gk_navTitle = model.groupName;
                chatVC.chatType = ChatTypeGroup;
                [self.navigationController pushViewController:chatVC animated:YES];
            }
            
            
        }
    }else if (indexPath.section ==2){
        //                公众号
        if (!_noFriend&&!_noGroup) {
            if (!_noPublic) {
                PublicModel * model = _friendAndGroupDataAry[indexPath.section][indexPath.row];
                PublicArticleViewController*vc=[[PublicArticleViewController alloc]init];
                vc.gk_navTitle = model.title;
                vc.publicUdid = model.udid;
                [self.navigationController pushViewController:vc animated:YES];
            }else{
                //        聊天记录
                ChatRecodeViewController * chatRecodeVC = [[ChatRecodeViewController alloc]init];
                chatRecodeVC.dataAry = self.friendAndGroupDataAry[indexPath.section][indexPath.row];
                [self.navigationController pushViewController:chatRecodeVC animated:YES];
            }
            
        }else{
            //        聊天记录
            ChatRecodeViewController * chatRecodeVC = [[ChatRecodeViewController alloc]init];
            chatRecodeVC.dataAry = self.friendAndGroupDataAry[indexPath.section][indexPath.row];
            [self.navigationController pushViewController:chatRecodeVC animated:YES];
        }
        
    } else
    {
        //        聊天记录
        ChatRecodeViewController * chatRecodeVC = [[ChatRecodeViewController alloc]init];
        chatRecodeVC.dataAry = self.friendAndGroupDataAry[indexPath.section][indexPath.row];
        [self.navigationController pushViewController:chatRecodeVC animated:YES];
        
    }
    NSLog(@"点击 === %@",indexPath);
    /*
     if ([self.collerType isEqualToString:@"搜索群"]) {
     ContactorModel * model= self.searchResultsArray[indexPath.row];
     GroupInfoViewController * groupInfoVC=[[GroupInfoViewController alloc]init];
     groupInfoVC.type=5;
     groupInfoVC.groupModel=model;
     groupInfoVC.groupId=[model.user_id integerValue];
     [self.navigationController pushViewController:groupInfoVC animated:YES];
     }else if ([self.collerType isEqualToString:@"4"])
     {
     ContactorModel * model= self.searchResultsArray[indexPath.section][indexPath.row];
     //        BTIMLog(@"选中的===%@",model.mj_keyValues);
     ChattingVC * chatvc=[[ChattingVC alloc]init];
     if ([model.is_group isEqualToString:@"friend"]) {
     
     //            BTIMLog(@"发送消息");
     chatVC.gk_navTitle = model.nickname;
     chatvc.receiverId = model.user_id.integerValue;
     chatvc.type = @"friend";
     [self.navigationController pushViewController:chatvc animated:YES];
     }else
     {
     chatVC.gk_navTitle = model.groupName;
     chatvc.receiverId = [model.user_id integerValue];
     chatvc.type = @"group";
     [self.navigationController pushViewController:chatvc animated:YES];
     
     }
     
     }else
     {
     ContactorModel * model= self.searchResultsArray[indexPath.row];
     UserInfoViewController * userInfoVC= [[UserInfoViewController alloc]init];
     //    userInfoVC.user_id=[model.user_id integerValue];
     userInfoVC.contactorModel=model;
     userInfoVC.type=@"addFirendsVC";
     [self.navigationController pushViewController:userInfoVC animated:YES];
     }
     */
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    //    if ([self.collerType isEqualToString:@"4"]) {
    //        return self.searchResultsArray.count;
    //    }else
    //    {
    if (![_controllerType isEqualToString:@"searchFriend"]) {
        
        return self.friendAndGroupDataAry.count;
        
    }
    return self.searchResultsArray.count;
    //    }
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (![_controllerType isEqualToString:@"searchFriend"]) {
        return [self.friendAndGroupDataAry[section]count];
    }
    return [self.searchResultsArray[section]count];
    
    //    return 2;
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    FirendsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"searchCell"];
    if (_noFriend) {
        if (_noGroup) {
            if (_noPublic) {
                
                NSArray * dataArr = self.friendAndGroupDataAry[indexPath.section][indexPath.row];
                BTMessageModel * msgModel = dataArr[0];//数据相同，取第一个赋值就可
                if (msgModel.chatType == ChatTypeFriend) {
                    cell.nicknameLbl.text = msgModel.nickname;
                    if ([msgModel.head containsString:@"http://"] ||[msgModel.head containsString:@"https://"]) {
                        [cell.userAvatar sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",msgModel.head]] placeholderImage:[UIImage imageNamed:@"bg_pyqtx"] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
                            
                            cell.userAvatar.image = image;
                        }];
                    }else{
                        [cell.userAvatar sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",userHeaderImage,msgModel.head]] placeholderImage:[UIImage imageNamed:@"bg_pyqtx"] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
                            
                            cell.userAvatar.image = image;
                        }];
                    }
                    
                    cell.contentLbl.hidden = NO;
                    cell.contentLbl.text = [NSString stringWithFormat:@"%ld条相关聊天记录",dataArr.count];
                    
                }else{
                    ContactModel * groupModel = [[UserDataBaseTool shareUserDataBaseTool] queryGroup:msgModel.gId];
                    cell.nicknameLbl.text = groupModel.groupName;
                    [cell.userAvatar sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",userHeaderImage,groupModel.groupHead]] placeholderImage:[UIImage imageNamed:@"bg_pyqtx"] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
                        
                        cell.userAvatar.image = image;
                    }];
                    cell.contentLbl.hidden = NO;
                    cell.contentLbl.text = [NSString stringWithFormat:@"%ld条相关聊天记录",dataArr.count];
                }
                
                cell.contentLbl.hidden = NO;
                cell.contentLbl.text = [NSString stringWithFormat:@"%ld条相关聊天记录",dataArr.count];
            }else{
                //公众号
                if (indexPath.section==0) {
                    cell.pubModel = self.friendAndGroupDataAry[indexPath.section][indexPath.row];
                    cell.contentLbl.hidden = YES;
                }else{
                    NSArray * dataArr = self.friendAndGroupDataAry[indexPath.section][indexPath.row];
                    BTMessageModel * msgModel = dataArr[0];//数据相同，取第一个赋值就可
                    if (msgModel.chatType == ChatTypeFriend) {
                        cell.nicknameLbl.text = msgModel.nickname;
                        if ([msgModel.head containsString:@"http://"] ||[msgModel.head containsString:@"https://"]) {
                            [cell.userAvatar sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",msgModel.head]] placeholderImage:[UIImage imageNamed:@"bg_pyqtx"] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
                                
                                cell.userAvatar.image = image;
                            }];
                        }else{
                            [cell.userAvatar sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",userHeaderImage,msgModel.head]] placeholderImage:[UIImage imageNamed:@"bg_pyqtx"] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
                                
                                cell.userAvatar.image = image;
                            }];
                        }
                        cell.contentLbl.hidden = NO;
                        cell.contentLbl.text = [NSString stringWithFormat:@"%ld条相关聊天记录",dataArr.count];
                    }
                }
                
            }
        }else{
            if (indexPath.section == 0) {
                
                cell.model = self.friendAndGroupDataAry[indexPath.section][indexPath.row];
                cell.contentLbl.hidden = YES;
            }else{
                if (_noPublic) {
                    NSArray * dataArr = self.friendAndGroupDataAry[indexPath.section][indexPath.row];
                    BTMessageModel * msgModel = dataArr[0];//数据相同，取第一个赋值就可
                    if (msgModel.chatType == ChatTypeFriend) {
                        cell.nicknameLbl.text = msgModel.nickname;
                        //                                       NSData * headData = [NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",userHeaderImage,msgModel.head]]];
                        //                                       cell.userAvatar.image = [UIImage imageWithData:headData];
                        if ([msgModel.head containsString:@"http://"] ||[msgModel.head containsString:@"https://"]) {
                            [cell.userAvatar sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",msgModel.head]] placeholderImage:[UIImage imageNamed:@"bg_pyqtx"] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
                                
                                cell.userAvatar.image = image;
                            }];
                        }else{
                            [cell.userAvatar sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",userHeaderImage,msgModel.head]] placeholderImage:[UIImage imageNamed:@"bg_pyqtx"] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
                                
                                cell.userAvatar.image = image;
                            }];
                        }
                        cell.contentLbl.hidden = NO;
                        cell.contentLbl.text = [NSString stringWithFormat:@"%ld条相关聊天记录",dataArr.count];
                        
                    }else{
                        ContactModel * groupModel = [[UserDataBaseTool shareUserDataBaseTool] queryGroup:msgModel.gId];
                        cell.nicknameLbl.text = groupModel.groupName;
                        [cell.userAvatar sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",userHeaderImage,groupModel.groupHead]] placeholderImage:[UIImage imageNamed:@"bg_pyqtx"] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
                            
                            cell.userAvatar.image = image;
                        }];
                        cell.contentLbl.hidden = NO;
                        cell.contentLbl.text = [NSString stringWithFormat:@"%ld条相关聊天记录",dataArr.count];
                    }
                    
                    cell.contentLbl.hidden = NO;
                    cell.contentLbl.text = [NSString stringWithFormat:@"%ld条相关聊天记录",dataArr.count];
                    
                }else{
                    cell.pubModel = self.friendAndGroupDataAry[indexPath.section][indexPath.row];
                    cell.contentLbl.hidden = YES;
                }
                
                
            }
        }
    }else{
        if (indexPath.section == 0) {
            cell.model = self.friendAndGroupDataAry[indexPath.section][indexPath.row];
            cell.contentLbl.hidden = YES;
        }else if(indexPath.section == 1){
            if (_noGroup) {
                if (_noPublic) {
                    //                聊天记录
                    NSArray * dataArr = self.friendAndGroupDataAry[indexPath.section][indexPath.row];
                    BTMessageModel * msgModel = dataArr[0];//数据相同，取第一个赋值就可
                    if (msgModel.chatType == ChatTypeFriend) {
                        cell.nicknameLbl.text = msgModel.nickname;
                        if ([msgModel.head containsString:@"http://"] ||[msgModel.head containsString:@"https://"]) {
                            [cell.userAvatar sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",msgModel.head]] placeholderImage:[UIImage imageNamed:@"bg_pyqtx"] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
                                
                                cell.userAvatar.image = image;
                            }];
                        }else{
                            [cell.userAvatar sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",userHeaderImage,msgModel.head]] placeholderImage:[UIImage imageNamed:@"bg_pyqtx"] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
                                
                                cell.userAvatar.image = image;
                            }];
                        }
                        cell.contentLbl.hidden = NO;
                        cell.contentLbl.text = [NSString stringWithFormat:@"%ld条相关聊天记录",dataArr.count];
                        
                    }else{
                        ContactModel * groupModel = [[UserDataBaseTool shareUserDataBaseTool] queryGroup:msgModel.gId];
                        cell.nicknameLbl.text = groupModel.groupName;
                        [cell.userAvatar sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",userHeaderImage,groupModel.groupHead]] placeholderImage:[UIImage imageNamed:@"bg_pyqtx"] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
                            
                            cell.userAvatar.image = image;
                        }];
                        cell.contentLbl.hidden = NO;
                        cell.contentLbl.text = [NSString stringWithFormat:@"%ld条相关聊天记录",dataArr.count];
                    }
                    
                    cell.contentLbl.hidden = NO;
                    cell.contentLbl.text = [NSString stringWithFormat:@"%ld条相关聊天记录",dataArr.count];
                }else{
                    cell.pubModel = self.friendAndGroupDataAry[indexPath.section][indexPath.row];
                    cell.contentLbl.hidden = YES;
                }
                
                
            }else{
                cell.model = self.friendAndGroupDataAry[indexPath.section][indexPath.row];
                cell.contentLbl.hidden = YES;
            }
        }else if(indexPath.section == 2){
            if (_noPublic) {
                //            聊天记录
                NSArray * dataArr = self.friendAndGroupDataAry[indexPath.section][indexPath.row];
                BTMessageModel * msgModel = dataArr[0];//数据相同，取第一个赋值就可
                if (msgModel.chatType == ChatTypeFriend) {
                    cell.nicknameLbl.text = msgModel.nickname;
                    if ([msgModel.head containsString:@"http://"] ||[msgModel.head containsString:@"https://"]) {
                        [cell.userAvatar sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",msgModel.head]] placeholderImage:[UIImage imageNamed:@"bg_pyqtx"] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
                            
                            cell.userAvatar.image = image;
                        }];
                    }else{
                        [cell.userAvatar sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",userHeaderImage,msgModel.head]] placeholderImage:[UIImage imageNamed:@"bg_pyqtx"] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
                            
                            cell.userAvatar.image = image;
                        }];
                    }
                    cell.contentLbl.hidden = NO;
                    cell.contentLbl.text = [NSString stringWithFormat:@"%ld条相关聊天记录",dataArr.count];
                    
                }else{
                    ContactModel * groupModel = [[UserDataBaseTool shareUserDataBaseTool] queryGroup:msgModel.gId];
                    cell.nicknameLbl.text = groupModel.groupName;
                    [cell.userAvatar sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",userHeaderImage,groupModel.groupHead]] placeholderImage:[UIImage imageNamed:@"bg_pyqtx"] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
                        
                        cell.userAvatar.image = image;
                    }];
                    cell.contentLbl.hidden = NO;
                    cell.contentLbl.text = [NSString stringWithFormat:@"%ld条相关聊天记录",dataArr.count];
                }
                
                cell.contentLbl.hidden = NO;
                cell.contentLbl.text = [NSString stringWithFormat:@"%ld条相关聊天记录",dataArr.count];
                
            }else{
                if (!_noFriend &&!_noGroup && !_noPublic) {
                    cell.pubModel = self.friendAndGroupDataAry[indexPath.section][indexPath.row];
                    cell.contentLbl.hidden = YES;
                }else{
                    //            聊天记录
                    NSArray * dataArr = self.friendAndGroupDataAry[indexPath.section][indexPath.row];
                    BTMessageModel * msgModel = dataArr[0];//数据相同，取第一个赋值就可
                    if (msgModel.chatType == ChatTypeFriend) {
                        cell.nicknameLbl.text = msgModel.nickname;
                        if ([msgModel.head containsString:@"http://"] ||[msgModel.head containsString:@"https://"]) {
                            [cell.userAvatar sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",msgModel.head]] placeholderImage:[UIImage imageNamed:@"bg_pyqtx"] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
                                
                                cell.userAvatar.image = image;
                            }];
                        }else{
                            [cell.userAvatar sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",userHeaderImage,msgModel.head]] placeholderImage:[UIImage imageNamed:@"bg_pyqtx"] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
                                
                                cell.userAvatar.image = image;
                            }];
                        }
                        cell.contentLbl.hidden = NO;
                        cell.contentLbl.text = [NSString stringWithFormat:@"%ld条相关聊天记录",dataArr.count];
                        
                    }else{
                        ContactModel * groupModel = [[UserDataBaseTool shareUserDataBaseTool] queryGroup:msgModel.gId];
                        cell.nicknameLbl.text = groupModel.groupName;
                        [cell.userAvatar sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",userHeaderImage,groupModel.groupHead]] placeholderImage:[UIImage imageNamed:@"bg_pyqtx"] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
                            
                            cell.userAvatar.image = image;
                        }];
                        cell.contentLbl.hidden = NO;
                        cell.contentLbl.text = [NSString stringWithFormat:@"%ld条相关聊天记录",dataArr.count];
                    }
                    
                    cell.contentLbl.hidden = NO;
                    cell.contentLbl.text = [NSString stringWithFormat:@"%ld条相关聊天记录",dataArr.count];
                }
                
            }
        }else{
            //            聊天记录
            NSArray * dataArr = self.friendAndGroupDataAry[indexPath.section][indexPath.row];
            BTMessageModel * msgModel = dataArr[0];//数据相同，取第一个赋值就可
            if (msgModel.chatType == ChatTypeFriend) {
                cell.nicknameLbl.text = msgModel.nickname;
                if ([msgModel.head containsString:@"http://"] ||[msgModel.head containsString:@"https://"]) {
                    [cell.userAvatar sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",msgModel.head]] placeholderImage:[UIImage imageNamed:@"bg_pyqtx"] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
                        
                        cell.userAvatar.image = image;
                    }];
                }else{
                    [cell.userAvatar sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",userHeaderImage,msgModel.head]] placeholderImage:[UIImage imageNamed:@"bg_pyqtx"] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
                        
                        cell.userAvatar.image = image;
                    }];
                }
                cell.contentLbl.hidden = NO;
                cell.contentLbl.text = [NSString stringWithFormat:@"%ld条相关聊天记录",dataArr.count];
                
            }else{
                ContactModel * groupModel = [[UserDataBaseTool shareUserDataBaseTool] queryGroup:msgModel.gId];
                cell.nicknameLbl.text = groupModel.groupName;
                [cell.userAvatar sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",userHeaderImage,groupModel.groupHead]] placeholderImage:[UIImage imageNamed:@"bg_pyqtx"] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
                    
                    cell.userAvatar.image = image;
                }];
                cell.contentLbl.hidden = NO;
                cell.contentLbl.text = [NSString stringWithFormat:@"%ld条相关聊天记录",dataArr.count];
            }
            
            cell.contentLbl.hidden = NO;
            cell.contentLbl.text = [NSString stringWithFormat:@"%ld条相关聊天记录",dataArr.count];
            
        }
    }
    
    
    return cell;
    
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    [self.textField resignFirstResponder];
}
- (void)leftBtnBtnDidClickAction:(UIButton *)sender {
    [self.textField resignFirstResponder];
    [self.navigationController popViewControllerAnimated:YES];
}

- (NSAttributedString *)getAttributeWith:(id)sender
                                  string:(NSString *)string
                               orginFont:(CGFloat)orginFont
                              orginColor:(UIColor *)orginColor
                           attributeFont:(CGFloat)attributeFont
                          attributeColor:(UIColor *)attributeColor
{
    __block  NSMutableAttributedString *totalStr = [[NSMutableAttributedString alloc] initWithString:string];
    [totalStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:orginFont] range:NSMakeRange(0, string.length)];
    [totalStr addAttribute:NSForegroundColorAttributeName value:orginColor range:NSMakeRange(0, string.length)];
    
    if ([sender isKindOfClass:[NSArray class]]) {
        
        __block NSString *oringinStr = string;
        __weak typeof(self) weakSelf = self;
        
        [sender enumerateObjectsUsingBlock:^(NSString *  _Nonnull str, NSUInteger idx, BOOL * _Nonnull stop) {
            
            NSRange range = [oringinStr rangeOfString:str];
            [totalStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:attributeFont] range:range];
            [totalStr addAttribute:NSForegroundColorAttributeName value:attributeColor range:range];
            oringinStr = [oringinStr stringByReplacingCharactersInRange:range withString:[weakSelf getStringWithRange:range]];
        }];
        
    }else if ([sender isKindOfClass:[NSString class]]) {
        
        NSRange range = [string rangeOfString:sender];
        
        [totalStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:attributeFont] range:range];
        [totalStr addAttribute:NSForegroundColorAttributeName value:attributeColor range:range];
    }
    return totalStr;
}

- (NSString *)getStringWithRange:(NSRange)range
{
    NSMutableString *string = [NSMutableString string];
    for (int i = 0; i < range.length ; i++) {
        [string appendString:@" "];
    }
    return string;
}

- (UIView *)titleView {
    if (!_titleView) {
        _titleView = [[UIView alloc] init];
        _titleView.bounds = CGRectMake(10, 0, SCREEN_WIDTH - 60, 32);
        _titleView.backgroundColor = KHEXCOLOR(kGrayColor_f2);
        [_titleView configLayerWithBorderWidth:0 andWithCornerRadius:5 andWithBorderColor:[UIColor whiteColor]];
        
        UIImageView *imageView = [UIImageView new];
        imageView.image = [UIImage imageNamed:@"icon_sousuo"];
        imageView.frame = CGRectMake(20, 10, 13, 13);
        [_titleView addSubview:imageView];
        
        _textField = [[UITextField alloc] init];
        _textField.font = [UIFont systemFontOfSize:13];
        //        _textField.placeholder = @"请输入内容搜索";
        _textField.frame = CGRectMake(40, 0, SCREEN_WIDTH - 100, 32);
        _textField.returnKeyType = UIReturnKeySearch;
        _textField.clearButtonMode = UITextFieldViewModeWhileEditing;
        _textField.delegate = self;
        [_textField addTarget:self action:@selector(textFieldTextChange:) forControlEvents:UIControlEventEditingChanged];
        [_titleView addSubview:_textField];
    }
    return _titleView;
}
-(MJTableViewNullDataView*)nullDataView
{
    if (!_nullDataView) {
        _nullDataView=[[MJTableViewNullDataView alloc]initWithFrame:CGRectMake(0,0*SCALAE, _searchResultsTable.frame.size.width, _searchResultsTable.frame.size.height)];
        _nullDataView.hidden=YES;
        _nullDataView.backgroundColor=[UIColor whiteColor];
    }
    [_nullDataView setCustomViewFrame:@"加载失败" message:@"搜索无结果"];
    return _nullDataView;
}
-(NSMutableArray*)searchResultsArray
{
    if (!_searchResultsArray) {
        _searchResultsArray=[[NSMutableArray alloc]init];
    }
    return _searchResultsArray;
}
- (UIView *)tipView{
    if (!_tipView) {
        _tipView = [[UIView alloc]init];
        _tipView.backgroundColor = [UIColor whiteColor];
    }
    return _tipView;
}

-(UILabel *)tipLabel{
    if (!_tipLabel) {
        _tipLabel = [[UILabel alloc]init];
        _tipLabel.attributedText =  [self getAttributeWith:@[@"搜索："] string:@"搜索：" orginFont:14 orginColor:KHEXCOLOR(@"#4795EF") attributeFont:14 attributeColor:[UIColor colorWithHexString:@"#262B2F"]];;
    }
    return _tipLabel;
}

-(UIView *)footView{
    if (!_footView) {
        _footView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 159.f)];
    }
    return _footView;
}

- (NSMutableArray *)localChatDataAry{
    if (!_localChatDataAry) {
        _localChatDataAry = [NSMutableArray array];
    }
    return _localChatDataAry;
}

- (NSMutableArray *)friendsArr{
    if (!_friendsArr) {
        _friendsArr = [NSMutableArray array];
    }
    return _friendsArr;
}

- (NSMutableArray *)friendAndGroupDataAry{
    if (!_friendAndGroupDataAry) {
        _friendAndGroupDataAry = [NSMutableArray array];
    }
    return _friendAndGroupDataAry;
}

- (NSMutableArray *)groupsArr{
    if (!_groupsArr) {
        _groupsArr = [NSMutableArray array];
    }
    return _groupsArr;
}

//- (void)dealloc
//{
//    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidShowNotification object:nil];
//    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
//}
/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
